import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch, Link, } from "react-router-dom";
import { Layout, Progress, Card, List, Timeline, Skeleton, Badge, Row, Col, message } from "antd";
import { CheckconditionDataForPatrolpush, } from "../js/patrolpushapi.js";
import { punchCardDetialBySymbolApi, patrolRouteBySchoolApi } from "../js/api.js";
import { getSignature } from "../js/dangerpushapi.js";

const { Content, Sider } = Layout;
// const WX = require("jweixin-wechat");

class Patrolpush extends Component {

    constructor(props) {
        super(props);
        this.state = {

        };
    }

    componentDidMount() {
        // getSignature(window.location.href)
        //     .then(res => {
        //         WX.config({
        //             debug: false, //开启debug模式，在验证签名过程中会返回对应信息
        //             appId: res.data.appid,
        //             signature: res.data.signature,
        //             nonceStr: res.data.noncestr,
        //             timestamp: res.data.timestamp,
        //             jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage']// 必填，需要使用的JS接口列表
        //         });
        //     })
        //     .catch((e) => {
        //         if (e.response) {
        //             //请求已发出，服务器返回状态码不是2xx。
        //             console.info(e.response.data)
        //             console.info(e.response.status)
        //             console.info(e.response.headers)
        //         } else if (e.request) {
        //             // 请求已发出，但没有收到响应
        //             // e.request 在浏览器里是一个XMLHttpRequest实例，
        //             // 在node中是一个http.ClientRequest实例
        //             console.info(e.request)
        //         } else {
        //             //发送请求时异常，捕捉到错误
        //             console.info('error', e.message)
        //         }
        //         console.info(e.config)
        //     });

        let urlData = this.getUrlParam("state");
        //  let urlData = "13,2021-11-08"
        let date = urlData.split(",")[1];

        // message.info("打印信息====", urlData)
        // WX.ready(function () {
        //     var obj = {
        //         title: date + '巡更情况', // 分享标题
        //         desc: '点击查看' + date + '巡更情况详情！', // 分享描述
        //         link: 'https://tidukeji.cn/dailypush/index.html?state=' + urlData, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        //         // 该链接是重定向链接，因为需要获取用户code，但是该链接又无法直接写微信获取code的链接，
        //         // 所以需要点击后重新加载新的页面，来实现重定向，重新打开获取code的微信链接，实现获取用户信息的功能；
        //         imgUrl: 'https://tidukeji.cn/img/loginIcon.png', // 分享图标
        //         fail: function (res) {
        //             console.log(JSON.stringify(res));
        //         }
        //     };
        //     // 2.1 监听“分享给朋友”，按钮点击、自定义分享内容及分享结果接口
        //     WX.onMenuShareAppMessage(obj);

        //     // 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
        //     WX.onMenuShareTimeline(obj);
        // })
    }

    getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    render() {
        return (
            <Router basename="dailypush">
                <Layout style={{ backgroundColor: '#f5f5f5' }}>
                    <Content>
                        <Switch>
                            <Route path="/detail" component={SchoolPatrolpushDetail} />
                            <Route path="/" component={SchoolPatrolpushMain} />
                        </Switch>
                    </Content>
                </Layout>
            </Router>
        );
    }
}

class SchoolPatrolpushMain extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            schoolId: 0,
            should: 0,
            done: 0,

            confirmLoading: false,
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            confirmLoading: true,
        });

        let urlData = this.getUrlParam("state").split(",");
        // let urlData = "13,2021-11-08".split(",")
        let schoolId = urlData[0];
        let date = urlData[1];

        this.setState({
            schoolId: schoolId,
            date: date,
        });

        CheckconditionDataForPatrolpush(schoolId, date)
            .then((res2) => {
                //得到整个页面的数据
                let dataTemp = []
                res2.data.data.forEach((item, index) => {
                    let temp = {
                        timePeriod: item.createTime,
                        people: item.realName,
                        routeDoneNum: item.routeDoneNum,
                        symbol: item.symbol,
                        routeRightNum: item.routeRightNum,
                        routeName:item.routeName,
                        routeNameId:item.routeNameId,
                        routeNum:item.routeNum
                    };
                    dataTemp.push(temp);
                });
                //console.log(dataTemp);
                let percent = ((res2.data.done > res2.data.should ? (res2.data.should) : (res2.data.done)) / res2.data.should * 100).toFixed(2);
                if (percent == 100) {
                    percent = Number(percent).toFixed(0);
                }

                this.setState({
                    data: dataTemp.reverse(),
                    routeNum: res2.data.routeNum,
                    should: res2.data.should,
                    done: res2.data.done,
                    percent: percent,
                    schoolId: res2.data.schoolId,

                    confirmLoading: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

    }

    getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    render() {
        //console.log(percent);
        let cards = this.state.data.map((d, index) => {
            console.log(d.routeRightNum);
            let normative = (d.routeRightNum / d.routeNum * 100).toFixed(2); //打卡规范性(准确率)
            if (normative == 100) {
                normative = Number(normative).toFixed(0);
            }
            // ((d.routeDoneNum > 23 ? 23 : d.routeDoneNum) / this.state.routeNum * 100).toFixed(2);
            let completionRate = (( d.routeDoneNum / d.routeNum ) * 100).toFixed(2);
            if (completionRate == 100) {
                completionRate = Number(completionRate).toFixed(0);
            }

            let data = [{
                title: '巡更路线',
                description: (<div style={{ color: '#000000' }}>{d.routeName}</div>)
            }, {
                title: '巡更人员',
                description: (<div style={{ color: '#000000' }}>{d.people}</div>)
            }, {
                title: '巡更点位',
                description: (<div style={{ color: '#000000' }}>{d.routeNum + '个'}</div>)
            }, {
                title: '实际巡更',
                description: (<div style={{ color: '#000000' }}>{d.routeDoneNum + '个'}</div>)
            },
            {
                title: '完成率',
                description: (<div style={{ color: '#000000' }}>{completionRate + '%'}</div>)
            }];

            return (
                <Link
                    style={{ textDecoration: 'none' }}
                    to={{
                        pathname: '/detail',
                        state: {
                            symbol: d.symbol,
                            schoolId: this.state.schoolId,
                            routeNameId:d.routeNameId,
                            completionRate:completionRate
                        }
                    }}>
                    <Card
                        key={index}
                        title={d.timePeriod}
                        extra={'详情 >'}
                        className='conditionCard'
                        bodyStyle={{
                            padding: '10px 24px',
                        }}>
                        <Layout>
                            <Content style={{ background: '#fff' }}>
                                <List
                                    itemLayout="horizontal"
                                    style={{ marginRight: 25 }}
                                    size="small"
                                    bordered={false}
                                    split={false}
                                    dataSource={data}
                                    renderItem={item => (
                                        <List.Item>
                                            <Row
                                                type="flex"
                                                justify="space-between"
                                                style={{
                                                    width: "100%"
                                                }}>
                                                <Col span={8} xs={10}>
                                                    {item.title}
                                                </Col>
                                                <Col
                                                    style={{ textAlign: "end" }}
                                                    span={16} xs={14}>
                                                    {item.description}
                                                </Col>
                                            </Row>
                                        </List.Item>
                                    )}
                                />
                            </Content>
                            <Sider width={'25%'} style={{ background: '#fff' }}>
                                <Progress
                                    className='progress-center'
                                    style={{
                                        fontSize: '12px'
                                    }}
                                    size='small'
                                    type="circle"
                                    percent={normative}
                                    width={85}
                                    strokeWidth={8}
                                    format={percent => `准确率${percent}%`}
                                />
                            </Sider>
                        </Layout>
                    </Card>
                </Link>
            )
        });


        return (
            <div style={{ paddingBottom: '10px' }}>
                <Skeleton loading={this.state.confirmLoading} active>
                    <div
                        className='conditionCard'
                        style={{
                            textAlign: 'center',
                            padding: '12px 24px',
                            background: '#ffffff',
                        }}>
                        <div>
                            日期：
                            {this.state.date}
                        </div>
                        <div>
                            <Progress
                                type="circle"
                                percent={this.state.percent}
                                width={150}
                                strokeWidth={8}
                                style={{ marginTop: '10px', fontSize: '28px' }}
                                format={percent => `完成率${percent}%`}
                            />
                        </div>
                        <div>
                            <Row style={{ marginTop: '10px', }}>
                                <Col span={12}>
                                    <Badge
                                        status="success"
                                        text={"已巡计划：" + this.state.done + "个"} />
                                </Col>
                                <Col span={12}>
                                    <Badge
                                        status="error"
                                        text={"未巡计划：" + (this.state.should - this.state.done) + "个"} />
                                </Col>
                            </Row>
                        </div>
                    </div>
                    <div style={{
                        width: '100%',
                        marginTop: '10px',
                    }}>
                        {cards}
                    </div>
                </Skeleton>
            </div>
        )
    }

}

class SchoolPatrolpushDetail extends Component {
    constructor(props) {
        super(props);
        // console.log(this.props.location.state.schoolId);
        this.state = {
            symbol: this.props.location.state.symbol,
            realShowDate: [],
            routeData: [],
            schoolId: this.props.location.state.schoolId,
            realname: '',
            time: '',
            true: '',
            finish: '',
            routeNameId:this.props.location.state.routeNameId,
            completionRate:this.props.location.state.completionRate,
            confirmLoading: false,
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            confirmLoading: true,
        });

        let checkPointAddress = []; //打卡数据的地点数据
        let routeData = []; //路线数据
        let realShowDate = []; //处理后数据
        punchCardDetialBySymbolApi(this.state.schoolId, this.state.symbol)
            .then((res) => {
                res.data.forEach((item, index) => {
                    realShowDate.push({
                        checkPointAddress: item.checkPointAddress,
                        createTime: item.createTime,
                        status: 1 //初始化状态，默认顺序都正确
                    });
                    checkPointAddress.push(item.checkPointAddress);
                })
                this.setState({
                    realname: res.data[0].realName,
                    time: res.data[0].createTime + "~" + res.data[res.data.length - 1].createTime
                });
                patrolRouteBySchoolApi(this.state.schoolId, this.state.routeNameId)
                    .then((res) => {
                        res.data.forEach((item, index) => {
                            routeData.push(item.address);
                        })
                        this.setState({
                            routeData: routeData
                        });
                        let missingPointAddress = [];
                        routeData.forEach((v, i) => {
                            if (checkPointAddress.indexOf(v) == -1) {
                                missingPointAddress.push(i);
                            }
                        });
                        //补齐打卡数据
                        missingPointAddress.forEach((v, i) => {
                            realShowDate.splice(v, 0, {
                                checkPointAddress: routeData[v],
                                createTime: "无",
                                status: 0 //遗漏打卡的点
                            });
                        });
                        //检验打卡顺序
                        realShowDate.forEach((v, i) => {
                            if (v.checkPointAddress != routeData[i]) {
                                v.status = -1; //顺序错误的点
                            }
                        });
                        let trueCheck = realShowDate.filter(v => {
                            if (v.status == 1) return v;
                        });

                        let trueData = (trueCheck.length / routeData.length * 100).toFixed(2);
                        if (trueData == 100) {
                            trueData = Number(trueData).toFixed(0);
                        }
                        // let finishData = (trueCheck.length > routeData.length ? routeData.length : trueCheck.length / routeData.length * 100).toFixed(2);
                        // if (finishData == 100) {
                        //     finishData = Number(finishData).toFixed(0);
                        // }
                        let finishData = this.state.completionRate

                        this.setState({
                            realShowDate: realShowDate,
                            true: trueData,
                            finish: finishData,

                            confirmLoading: false,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    render() {
        let timelineItem = this.state.realShowDate.map((d, index) => {
            return (
                <div
                    style={{
                        width: '100%',
                        marginTop: '10px',
                    }}>
                    {
                        (d.status == 0) ?
                            (
                                <Timeline.Item color={'#888888'}>
                                    <div style={{ fontSize: '18px', color: '#888888', display: 'inline-block', }}>
                                        {d.checkPointAddress}
                                    </div>
                                </Timeline.Item>
                            ) :
                            (
                                <Timeline.Item color={(d.status == 1) ? 'blue' : 'red'}>
                                    {
                                        (d.status == 1) ?
                                            (
                                                <div style={{ fontSize: '18px', color: '#000000', display: 'inline-block', }}>
                                                    {d.checkPointAddress}
                                                </div>
                                            ) :
                                            (
                                                <div style={{ fontSize: '18px', color: '#f5222d', display: 'inline-block', }}>
                                                    {this.state.routeData[index]}
                                                </div>
                                            )
                                    }
                                    <div style={{ color: '#888888', float: 'right', marginTop: '3px', display: 'inline-block', }}>
                                        {d.createTime}
                                    </div>
                                    {
                                        (d.status == 1) ?
                                            ('') :
                                            (<div style={{ fontSize: '12px', color: '#000000', }}>{d.checkPointAddress}</div>)
                                    }
                                </Timeline.Item>
                            )
                    }
                </div>
            )
        });

        return (
            <div style={{ paddingBottom: '10px' }}>
                <Skeleton loading={this.state.confirmLoading} active>
                    <div
                        className='conditionCard'
                        style={{
                            textAlign: 'center',
                            padding: '12px 24px',
                            background: '#ffffff',
                        }}>
                        <div>
                            时间：
                        {this.state.time}
                        </div>
                        <div>
                            <Progress
                                type="circle"
                                percent={this.state.true}
                                width={150}
                                strokeWidth={8}
                                style={{ marginTop: '10px', fontSize: '28px' }}
                                format={percent => `准确率${percent}%`}
                            />
                        </div>
                        <div>
                            <Row style={{ marginTop: '10px', }}>
                                <Col span={12}>
                                    <Badge
                                        status="processing"
                                        text={"完成率：" + (this.state.finish) + "%"} />
                                </Col>
                                <Col span={12}>
                                    <Badge
                                        status="Default"
                                        text={"人员：" + this.state.realname} />
                                </Col>
                            </Row>
                        </div>
                    </div>
                    <div
                        className='conditionCard'
                        style={{
                            marginTop: '10px',
                            backgroundColor: '#ffffff',
                            padding: '24px',
                        }}>
                        <Timeline style={{ marginTop: '10px' }}>{timelineItem}</Timeline>
                    </div>
                </Skeleton>
            </div>
        )
    }
}




















export default Patrolpush;
